#include<iostream>
#include<opencv2/opencv.hpp>
#include<vector>

using namespace cv;
using namespace std;

int main(){
    Mat image = imread("test.jpeg");
    if(image.empty()){
        cout<<"Can't recognize the image"<< endl;
        return -1;
    }
    Mat gray ,binary;

    cvtColor(image, gray ,COLOR_BGR2GRAY);
    threshold(gray,binary,0,255,THRESH_BINARY | THRESH_OTSU);
    
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(binary,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE);
    
    int validContours=0;
    for(size_t i=0;i<contours.size();i++){
      double area =contourArea(contours[i]);
      if (area>500){
      validContours++;
      }
    }

    Mat result = image.clone();
   int fontFace=FONT_HERSHEY_SIMPLEX;
   double fontScale=0.8;
   Scalar textColor(0,255,0);
   Scalar bgColor(0,0,0);
   int thickness=2;
   
   string text="outlines_Num:"+to_string(validContours);
   
   int baseline=0;
   Size textSize=getTextSize(text,fontFace,fontScale,thickness, &baseline);
   
   rectangle(result,Point(10,10), Point(20 + textSize.width, 40+textSize.height),bgColor,FILLED);
   putText(result,text,Point(15,30+textSize.height),fontFace,fontScale,textColor,thickness);
   
   for(size_t i=0 ;i<contours.size();i++){
       double area =contourArea(contours[i]);
       if (area>500){
    drawContours(result,contours,-1, Scalar(0,255,0),2);
    }
    }
  
  cout<<"detect"<<validContours<<"outlines"<<endl;
    imshow ("origin img",image);
    imshow("result img",result);
    waitKey(0);
        
    return 0;
}
